package com.example.ssdapp.bean;

import android.util.Log;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import java.util.StringTokenizer;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static java.security.AccessController.getContext;

/**
 * Created by 范晋瑜 on 2017/10/19.
 */

public class Post {
    private static final OkHttpClient sOkHttpClient = new OkHttpClient();
    private static final String TAG = "Post";

    public static String sendPostRequest(String url, String data) {

        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody requestBody = RequestBody.create(mediaType, data);
        Request request = new Request.Builder().url(url).post(requestBody).build();

        try {
            Response response = sOkHttpClient.newCall(request).execute();
            if (response != null) {
                String responseStr = response.body().string();
                Log.i(TAG, "sendPostRequest: "+responseStr);
                return responseStr;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String sendGetRequest(String url){
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = sOkHttpClient.newCall(request).execute();
            if (response != null) {
                String responseStr = response.body().string();
                Log.i(TAG, "sendPostRequest: "+responseStr);
                return responseStr;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
